﻿using com.kmer;
using com.kmer.ApiServer;
using com.kmer.ApiServer.Attributes;
using com.kmer.ApiServer.com.kmer.Model;
using com.kmer.Attributes;
using com.kmer.db;
using com.kmer.Helper;
using EntityFramework.Extensions;
using kmer.Helper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;


namespace BaseAPI
{
    /// <summary>
    /// 用户管理
    /// </summary>
    [Description("用户管理")]
    public class UsersHandler : BaseHandler
    {
        #region 构造函数
        private km_platformEntities db_context;

        public UsersHandler()
        {
            db_context = new km_platformEntities();
        }
        #endregion

        #region API
        [MustLogin]
        [Description("修改密码")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult SetPass(
            [ParamDescription("旧密码（MD5）")]string oldPass,
            [ParamDescription("新密码（MD5）")]string newPass,
            [ParamDescription("重复新密码（MD5）")]string newPassRepeated)
        {
            oldPass = oldPass.ToUpper();
            newPass = newPass.ToUpper();
            newPassRepeated = newPassRepeated.ToUpper();
            if (string.IsNullOrWhiteSpace(oldPass))
                return Error("旧密码不能为空", 4002);
            if (string.IsNullOrWhiteSpace(newPass))
                return Error("新密码不能为空", 4003);
            if (!oldPass.IsMD5Code())
                return Error("旧密码必须是MD5（32位）加密", 4002);
            if (!newPass.IsMD5Code())
                return Error("新密码必须是MD5（32位）加密", 4003);
            if (!newPass.Equals(newPassRepeated))
                return Error("新密码输入不一致", 4004);
            var data = db_context.sys_users.FirstOrDefault(item => item.UserID == this.CusID);
            if (data == null)
                return Error("没有找到相关记录", 4005);
            if (!data.PassWord.ToUpper().Equals(oldPass))
                return Error("输入的旧密码不正确", 4006);
            if (data.PassWord.ToUpper().Equals(newPass))
                return Error("新密码不能与旧密码相同", 4007);
            data.PassWord = newPass;
            try
            {
                db_context.SaveChanges();
                return Success(0);
            }
            catch
            {
                return Error("修改密码失败", 4008);
            }
        }

        [MustLogin]
        [Description("设置头像")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult SetAvater([ParamDescription("图片ID")]Guid imageId)
        {
            if (imageId != default(Guid))
            {
                var imgList = db_context.kmImages.Where(img => imageId == img.ID);
                if (!imgList.Any())
                    return Error("图片错误，请重新上传");
                var qsUser = db_context.kmAvatar.Where(t => t.UserID == this.CusID);
                if (qsUser.Any())
                    db_context.kmAvatar.Where(t => t.UserID == this.CusID).Delete();
                var yhAvatar = new kmAvatar
                {
                    UserID = this.CusID,
                    ImageID = imageId,
                    IsDefault = false
                };
                db_context.kmAvatar.Add(yhAvatar);
                try
                {
                    db_context.SaveChanges();
                }
                catch (Exception ex)
                {
                    return Error(ex.Message);
                }
            }
            return Success(0);
        }

        [MustLogin]
        [Description("设置头像(Base64格式)")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult SetAvatarBase64([ParamDescription("Base64")]string photoData)
        {
            if (string.IsNullOrWhiteSpace(photoData))
            {
                return Error("数据有误");
            }
            if (!photoData.StartsWith("data:image"))
            {
                var savePath = ConfigurationHelper.Get("avatar", @"D:\KMPlat\images\upfile\Avatar");
                //var path = serverPath + vPath.Substring(1);
                //var toSave = "~/upfile/appFace/";
                //var savePath = Server.MapPath(toSave);
                if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);
                var imgId = Guid.NewGuid();
                var name = imgId + ".jpg";
                savePath = Path.Combine(savePath, name);
                //var base64Data = photoData.Substring(22);
                try
                {
                    // if (db_context.kmAvatar.Any(t => t.UserID == this.CusID))
                    {
                        var avatar = db_context.kmAvatar.Where(t => t.UserID == this.CusID);
                        avatar.Delete();
                        db_context.kmImages.Where(t => avatar.Select(a => a.ImageID).Contains(t.ID)).Delete();
                        var kmImage = new kmImages
                        {
                            ID = imgId,
                            Url = Path.Combine("~/upfile/Avatar/", name),
                            Title = "app用户头像"
                        };
                        db_context.kmImages.Add(kmImage);
                        var kmAvatar = new kmAvatar
                        {
                            ImageID = imgId,
                            IsDefault = true,
                            UserID = this.CusID
                        };
                        db_context.kmAvatar.Add(kmAvatar);
                        var fs = File.Create(savePath);
                        var bytes = Convert.FromBase64String(photoData);
                        fs.Write(bytes, 0, bytes.Length);
                        fs.Close();

                        db_context.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "SAVE IMAGE(BASE64)");
                }
            }
            return Success(0);
        }

        /// <summary>
        /// 获取用户订单数据
        /// </summary>
        /// <returns></returns>
        [MustLogin]
        [Description("获取用户订单数据")]
        [ReturnType(typeof(UserOrderMain), "订单列表")]
        public ApiResult GetUserOrderMain()
        {
            try
            {
                //订货会数
                int orderFlag = db_context.t_order_master.Count(c => c.OrderFlag == false);
                int orderInNumber = 0, orderInNumber_Non = 0;
                //用户参与数
                var temp_master = db_context.t_order_GradeResult_Mater.Where(c => c.UserID == CusID).GroupBy(c => c.MasterID);
                orderInNumber = temp_master == null ? 0 : temp_master.Count();
                if (orderFlag > 0)
                {
                    orderInNumber_Non = orderFlag - orderInNumber;
                }
                List<SKC_OrderVM> list = new List<SKC_OrderVM>();
                var Maters = db_context.t_order_GradeResult_Mater.Where(c => c.UserID == CusID).Select(c => new { MasterID = c.MasterID, SerialNo = c.SerialNo });
                //查询出当前用户的订货ID
                var MasterIDs = Maters.Select(c => new { MasterID = c.MasterID }).Distinct();
                //查询出订单 Distinct()
                var order_item = db_context.t_order_master.Where(t => t.OrderFlag == false).OrderByDescending(c => c.CreateDate).Take(10).Select(c => new { MasterID = c.MasterID, OrderName = c.OrderName }).ToList();
                if (order_item != null && order_item.Count > 0)
                {
                    order_item.ForEach(c =>
                    {
                        int skcqty = 0, c_v_number = 0;
                        //查询SKC需求量
                        var m_skcrequire = db_context.t_order_SKCRequire.Where(s => s.MasterID == c.MasterID && s.SKCQty > 0).ToList();
                        skcqty = m_skcrequire == null ? 0 : m_skcrequire.Sum(d => d.SKCQty); 
                        //取出订货会的评价流水号
                        var SerialNos = Maters.Where(n => n.MasterID == c.MasterID)?.Select(n => new { SerialNo = n.SerialNo }).Distinct();
                        //查询订版量
                        c_v_number = db_context.t_order_ChooseVersion.Count(s => s.MasterID == c.MasterID && SerialNos.Any(d => d.SerialNo == s.SerialNo) && s.ChooseFlag == true);
                        list.Add(new SKC_OrderVM { MasterID = c.MasterID, OrderName = c.OrderName, SKCQty = skcqty, ChooseVersionNumber = c_v_number });
                    });
                }
                UserOrderMain userOrderMain = new UserOrderMain { OrderFlag = orderFlag, OrderInNumber = orderInNumber, OrderInNumber_Non = orderInNumber_Non, OrderList = list };
                return Success(userOrderMain);
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        #endregion
    }
}
